<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9" class="no-copy">
    <div class="container" style="width:75vw">
      <StuExamNavBar :examId="examId" :semesterId="semesterId" />
      <div class="exam-container">
        <div style="width: 100px; border-right: 2px dashed red; padding: 20px; background: #fff; text-align: center; font-size: 14px; white-space: nowrap;">
          <div class="exam-left-bar">
            <p class="vertical-text">学校：<span class="underline">{{ studentClass }}</span></p>
            <p class="vertical-text">学号：<span class="underline">{{ major }}</span></p>
            <p class="vertical-text">姓名：<span class="underline">{{ studentName }}</span></p>
          </div>
        </div>

        <div class="exam-content" :data-text="paperTitle">
          <div class="timer-bar">{{ formattedTime }}</div>

          <header class="exam-header">
            <h2>{{ paperTitle }}</h2>
            <p>共【{{ totalMajor }}大题】【{{ totalQuestions }}小题】满分【{{ totalScore }}分】 考试时长【{{ examDuration }}分钟】</p>
            <p style="font-size:12px; margin:30px 150px">试卷须知：{{ examInstructions }}</p>

            <table class="score-table">
              <thead>
                <tr>
                  <th>题型</th>
                  <th>单选题</th>
                  <th>多选题</th>
                  <th>判断题</th>
                  <th>简答题</th>
                  <th>总分</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>应得分</td>
                  <td>{{ expectedScores.singleChoice }}</td>
                  <td>{{ expectedScores.multipleChoice }}</td>
                  <td>{{ expectedScores.trueFalse }}</td>
                  <td>{{ expectedScores.shortAnswer }}</td>
                  <td>{{ totalScore }}</td>
                </tr>
                <tr>
                  <td>实得分</td>
                  <td>0.0</td>
                  <td>0.0</td>
                  <td>0.0</td>
                  <td>0.0</td>
                  <td>0.0</td>
                </tr>
              </tbody>
            </table>
          </header>

          <section class="exam-questions" v-for="(questionGroup, index) in questionGroups" :key="index">
            <h3 style="padding:10px 0px">{{ index + 1 }}. {{ questionGroup.title }} <span class="blue-text">(共{{ questionGroup.questions.length }}题；共{{ questionGroup.totalScore }}分)</span></h3>

            <div v-for="(question, qIndex) in questionGroup.questions" :key="qIndex" class="question">
              <p><span>{{ qIndex + 1 }}. {{ question.title }} <span class="blue-text">({{ question.score }}分)</span></span></p>

              <ul v-if="question.type === 'only_sel' || question.type === 'yesorno'">
                <li v-for="(option, oIndex) in question.options" :key="oIndex">
                  <input 
                    type="radio" 
                    :name="'q' + question.id" 
                    :checked="option.selected"
                    :disabled="isSubmitted" 
                    @change="handleAnswerChange(question.id, oIndex)">
                  {{ String.fromCharCode(65 + oIndex) }}. {{ option.text }}
                </li>
              </ul>

              <ul v-if="question.type === 'many_sel'">
                <li v-for="(option, oIndex) in question.options" :key="oIndex">
                  <input 
                    type="checkbox" 
                    :name="'q' + question.id" 
                    :checked="option.selected"
                    :disabled="isSubmitted"
                    @change="handleMultiAnswerChange(question.id, oIndex)">
                  {{ String.fromCharCode(65 + oIndex) }}. {{ option.text }}
                </li>
              </ul>

              <div v-if="question.type === 'qna'">
                <QuillEditor
                  v-if="!isSubmitted"
                  v-model="userAnswers[question.id]"
                  @blur="handleTextAnswerChange(question.id, userAnswers[question.id])"
                  style="border: 1px solid #ccc; min-height: 150px; padding: 10px; background: white;"
                />
                <div v-else class="submitted-answer" v-html="userAnswers[question.id] || '<i>无答案</i>'"></div>
              </div>
            </div>
          </section>

          <div v-if="!isSubmitted" style="text-align:end; margin:30px 0;">
            <button @click="manualSaveAnswers" class="save-button">暂存作答</button>
            <button @click="submitExam"  class="create-button">
              提交试卷
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import { ref, onMounted, computed, watch, toRefs,onUnmounted } from 'vue';
import StuExamNavBar from '@/components/StuExamNavBar.vue';
import { getPaperHeader, getPaperDetails, StusubmitExam } from '@/services/api';
import { getUserInfo } from '@/services/user';
import QuillEditor from '@/components/QuillEditor.vue';
import { ElMessage } from 'element-plus';
import { fetchStuExamDetail } from '@/services/api';
import { useRouter } from 'vue-router';


export default {
  name: 'StuPaperPreview',
  components: { StuExamNavBar, QuillEditor },
  props: {
    examId: [String, Number],
    semesterId: [String, Number]
  },
  setup(props) {
    const { examId } = toRefs(props); 
    const startKey = `start_time_${examId.value}`;
    const router = useRouter();
    const paperId = ref(localStorage.getItem('currentPaperId'));
    const paperTitle = ref('');
    const examDuration = ref(parseInt(localStorage.getItem('during_time')) || 60); //默认60分钟
    const isSubmitted = ref(localStorage.getItem('is_submit') === 'true');
    let storedStart = localStorage.getItem(startKey);
    if (!storedStart) {
      storedStart = new Date().toISOString();
      localStorage.setItem(startKey, storedStart);
    }
    const startTime = ref(new Date(storedStart));
    let autoSaveTimer = null;
    const studentClass = ref('');
    const major = ref('');
    const studentName = ref('');
    const examInstructions = ref('');
    const totalMajor = ref(0);
    const totalQuestions = ref(0);
    const totalScore = ref(0);
    const questionGroups = ref([]);
    const examStatus = ref(localStorage.getItem('currentExamStatus'));
    const expectedScores = ref({
      singleChoice: 0,
      multipleChoice: 0,
      trueFalse: 0,
      shortAnswer: 0
    });
    const userAnswers = ref({});
    const userId = ref(localStorage.getItem('id')); // 假设用户ID从localStorage获取

    const fetchUserInfo = async () => {
      try {
        const res = await getUserInfo(userId.value);
        const data = res.data.data;
        studentName.value = data.username;
        studentClass.value = data.stu_number;
        major.value = data.university_name;
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };
    const fetchStuExamRecord = async () => {
      try {
        const res = await fetchStuExamDetail(paperId.value, props.semesterId, localStorage.getItem('stu_exam_id'), userId.value);
        if (res.data && res.data.status === 1) {
          const { paperHeader, qsList } = res.data.data;
          paperTitle.value = stripHtmlTags(paperHeader.paper_title);
          totalScore.value = paperHeader.max_score;

          const grouped = {};
          for (const item of qsList) {
            if (!grouped[item.paper_format_id]) {
              grouped[item.paper_format_id] = {
                title: stripHtmlTags(item.format_content),
                totalScore: item.format_score,
                questions: []
              };
            }
            for (const q of item.items) {
              const question = {
                id: q.qs_id,
                title: stripHtmlTags(q.qs_title),
                score: q.q_score,
                type: q.qs_type,
                options: q.options ? q.options.map(opt => ({
                  id: opt.option_id,
                  text: stripHtmlTags(opt.option_content),
                  correct: opt.is_right,
                  selected: opt.stu_choosed // 关键在这里
                })) : [],
              };
              grouped[item.paper_format_id].questions.push(question);

              // 回显学生答案
              if (q.qs_type === 'only_sel' || q.qs_type === 'yesorno') {
                userAnswers.value[q.qs_id] = q.stu_ansIds?.[0] || null;
              } else if (q.qs_type === 'many_sel') {
                userAnswers.value[q.qs_id] = q.stu_ansIds || [];
              } else if (q.qs_type === 'qna') {
                userAnswers.value[q.qs_id] = q.stu_ans || '';
              }
            }
          }

          questionGroups.value = Object.values(grouped);
          totalMajor.value = Object.keys(grouped).length;
          totalQuestions.value = Object.values(grouped).reduce((sum, group) => sum + group.questions.length, 0);
        }
      } catch (err) {
        console.error('回显失败:', err);
      }
    };

    const stripHtmlTags = (str) => str.replace(/<\/?[^>]+(>|$)/g, "");

   // 修改单选处理逻辑
    const handleAnswerChange = (questionId, optionIndex) => {
      const selectedOption = questionGroups.value
        .flatMap(g => g.questions)
        .find(q => q.id === questionId)
        ?.options[optionIndex];
      
      if (selectedOption) {
        userAnswers.value[questionId] = selectedOption.id; // 存储option_id
      }
    };

    // 修改多选处理逻辑  
    const handleMultiAnswerChange = (questionId, optionIndex) => {
      const question = questionGroups.value
        .flatMap(g => g.questions)
        .find(q => q.id === questionId);
      
      if (question) {
        const selectedOption = question.options[optionIndex];
        if (!userAnswers.value[questionId]) {
          userAnswers.value[questionId] = [];
        }
        
        const idx = userAnswers.value[questionId].indexOf(selectedOption.id);
        if (idx > -1) {
          userAnswers.value[questionId].splice(idx, 1);
        } else {
          userAnswers.value[questionId].push(selectedOption.id);
        }
      }
    };
    const handleTextAnswerChange = (questionId, text) => {
      // 对于问答题，直接存储学生的答案
      userAnswers.value[questionId] = text;
    };

    const fetchPaperData = async () => {
      try {
        const headerResponse = await getPaperHeader(paperId.value);
        if (headerResponse.status === 200 && headerResponse.data.status === 1) {
          paperTitle.value = stripHtmlTags(headerResponse.data.data.paper_title);
          examInstructions.value = stripHtmlTags(headerResponse.data.data.paper_content);
        }

        const detailsResponse = await getPaperDetails(paperId.value);
        if (detailsResponse.status === 200 && detailsResponse.data.status === 1) {
          const paperData = detailsResponse.data.data;
          questionGroups.value = paperData.paperList.map(group => ({
            title: stripHtmlTags(group.format_content),
            totalScore: group.format_score,
            questions: group.items.map(item => ({
              id: item.qs_id,
              title: stripHtmlTags(item.qs_title),
              score: item.q_score,
              type: item.qs_type,
              options: item.options ? item.options.map(opt => ({
                id: opt.option_id,  // 保留后端返回的option_id
                text: stripHtmlTags(opt.option_content),
                correct: opt.is_right
              })) : [],
            }))
          }));
          totalScore.value = paperData.paperHeader.max_score;
          totalMajor.value = paperData.paperList.length;
          totalQuestions.value = paperData.paperList.reduce((sum, group) => sum + group.format_qs_cnt, 0);
        }
      } catch (error) {
        console.error('Error fetching paper data:', error);
      }
    };

    const now = ref(new Date());

   const remainingTime = computed(() => {
      if (examStatus.value === '2') return 0;
      const elapsed = Math.round((now.value - startTime.value) / 1000);
      const totalSeconds = examDuration.value * 60;
      return Math.max(0, totalSeconds - elapsed);
    });
    const manualSaveAnswers = () => {
      if (examStatus.value === '2') {
        ElMessage.warning('考试已截止，无法暂存作答');
        return;
      }
      saveFullAnswers();
      ElMessage.success('作答已暂存');
    };
    const startAutoSave = () => {
      autoSaveTimer = setInterval(() => {
        saveFullAnswers();
      }, 60 * 1000); // 每分钟一次
    };
    const saveFullAnswers = () => {
      // 同步选中状态
      for (const group of questionGroups.value) {
        for (const question of group.questions) {
          if (question.type === 'only_sel' || question.type === 'yesorno') {
            for (const opt of question.options) {
              opt.selected = userAnswers.value[question.id] === opt.id;
            }
          } else if (question.type === 'many_sel') {
            for (const opt of question.options) {
              opt.selected = (userAnswers.value[question.id] || []).includes(opt.id);
            }
          }
          // 问答题不需要同步 selected，内容已存在 userAnswers
        }
      }

      const answerData = JSON.stringify(questionGroups.value);
      localStorage.setItem(`answer_full_${examId.value}`, answerData);
    };
    
    const restoreFullAnswers = () => {
      const cached = localStorage.getItem(`answer_full_${examId.value}`);
      if (!cached) return;
      try {
        const parsed = JSON.parse(cached);
        questionGroups.value = parsed;

        // 同步 userAnswers（因为提交仍基于 userAnswers）
        for (const group of parsed) {
          for (const q of group.questions) {
            if (q.type === 'only_sel' || q.type === 'yesorno') {
              const sel = q.options.find(opt => opt.selected);
              if (sel) userAnswers.value[q.id] = sel.id;
            } else if (q.type === 'many_sel') {
              userAnswers.value[q.id] = q.options.filter(opt => opt.selected).map(opt => opt.id);
            } else if (q.type === 'qna') {
              userAnswers.value[q.id] = userAnswers.value[q.id] || ''; // 保留原内容
            }
          }
        }
      } catch (e) {
        console.error('作答恢复失败:', e);
      }
    };



   const submitExam = async () => {
     if (examStatus.value === '2') {
    ElMessage.warning('考试已截止，无法提交试卷');
    return;
  }
    const questions = [];
    // 创建日期对象并格式化
    const now = new Date();
    const startTimeObj = new Date(localStorage.getItem(`start_time_${examId.value}`));
    const formatStartTime = `${startTimeObj.getFullYear()}-${(startTimeObj.getMonth()+1).toString().padStart(2, '0')}-${startTimeObj.getDate().toString().padStart(2, '0')} ${startTimeObj.getHours().toString().padStart(2, '0')}:${startTimeObj.getMinutes().toString().padStart(2, '0')}:${startTimeObj.getSeconds().toString().padStart(2, '0')}`;
    const formatTime = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
    for (const questionGroup of questionGroups.value) {
      for (const question of questionGroup.questions) {
        if (question.type === 'only_sel' || question.type === 'yesorno') {
          // 选择题或判断题，填充 ans_ids 数组
          questions.push({
            qs_id: question.id,
            qs_type: question.type,
            ans_ids: userAnswers.value[question.id] ? [userAnswers.value[question.id]] : [], // 用户选择的选项
          });
        } else if (question.type === 'many_sel') {
          // 多选题，填充 ans_ids 数组
          questions.push({
            qs_id: question.id,
            qs_type: question.type,
            ans_ids: userAnswers.value[question.id] || [], // 用户选择的多个选项
          });
        } else if (question.type === 'qna') {
          // 问答题，填充 right_ans 字段
          questions.push({
            qs_id: question.id,
            qs_type: question.type,
            ans: userAnswers.value[question.id] || "", // 学生的回答内容
          });
        }
      }
    }

    // 构建提交数据
    const data = {
      paper_id: paperId.value, // 获取试卷 ID
      exam_id: localStorage.getItem('currentExamId'),  // 获取考试 ID
      user_id: userId.value,
      submit_time: formatTime, // 获取提交时间
      start_time: formatStartTime, // 获取开始时间
      questions: questions,
    };
    // 修改提交后的响应处理
      try {
        const res = await StusubmitExam(data);
        // 修改判断条件，根据实际返回数据结构
        if (res.data && res.data.status === 1) {  // 正确判断状态
         sessionStorage.removeItem(`exam_confirmed_${examId.value}`);
          localStorage.setItem('stu_exam_id', res.data.data);
          ElMessage.success('提交成功');
          isSubmitted.value = true;
          localStorage.setItem('is_submit', 'true');
          localStorage.removeItem('activeExamId');
          localStorage.removeItem(`start_time_${examId.value}`);
          localStorage.removeItem(`answer_full_${examId.value}`);
          router.push({
            name: 'StuAnswerReview',
            params: {
              semesterId: props.semesterId,
              examId: localStorage.getItem('currentExamId'),
              stu_exam_id: localStorage.getItem('stu_exam_id'),
              paper_id: paperId.value
            }
          });
        } else {
          ElMessage.error(`提交失败: ${res.data?.msg || '未知错误'}`); // 显示具体错误信息
        }
      } catch (error) {
        console.error('提交试卷失败:', error);
        ElMessage.error(`请求异常: ${error.message}`); // 增加异常提示
      }
    };

    onMounted(() => {
      const updateTime = () => {
        now.value = new Date();
        const delay = 1000 - (now.value.getTime() % 1000); // 精准对齐每秒
        setTimeout(updateTime, delay);
      };
      updateTime();

      fetchUserInfo();

      if (isSubmitted.value) {
        fetchStuExamRecord(); // 已提交：回显作答
      } else {
        // 设置或恢复开始时间
        const key = `start_time_${examId.value}`;
        let stored = localStorage.getItem(key);
        if (!stored) {
          stored = new Date().toISOString();
          localStorage.setItem(key, stored);
        }
        startTime.value = new Date(stored);

        // 获取试题结构
        fetchPaperData().then(() => {
          restoreFullAnswers(); // 尝试恢复完整作答内容
        });
      }
       startAutoSave();
      // 离开页面时保存作答
      window.addEventListener('beforeunload', saveFullAnswers);
    });
    onUnmounted(() => {
      if (autoSaveTimer) clearInterval(autoSaveTimer); // 清除定时器
      window.removeEventListener('beforeunload', saveFullAnswers);
    });

    watch(remainingTime, (newVal) => {
      if (newVal === 0 && !isSubmitted.value) {
        isSubmitted.value = true;
        ElMessage.warning('考试时间已到，自动交卷');
        submitExam();
      }
    });

    const formattedTime = computed(() => {
      if (examStatus.value === '2' || isSubmitted.value) return '00:00';
      const m = String(Math.floor(remainingTime.value / 60)).padStart(2, '0');
      const s = String(remainingTime.value % 60).padStart(2, '0');
      return `${m}:${s}`;
    });
    
    return {
      paperTitle,
      examDuration,
      studentClass,
      major,
      studentName,
      totalMajor,
      totalQuestions,
      totalScore,
      questionGroups,
      expectedScores,
      examInstructions,
      userAnswers,
      handleAnswerChange,
      handleMultiAnswerChange,
      handleTextAnswerChange,
      isSubmitted,
      submitExam,
      formattedTime,
      examStatus,
      saveFullAnswers,
      manualSaveAnswers,
    };
  }
};
</script>

<style scoped>
.submitted-answer {
  border: 1px dashed #ccc;
  background-color: #fafafa;
  padding: 15px;
  min-height: 150px;
  font-size: 15px;
  color: #333;
}
/* 禁止复制 */
.no-copy {
  user-select: none;
}

/* 倒计时条 */
.timer-bar {
  position: fixed;
  top: 20px;
  left: 93%;
  transform: translateX(-50%);
  background: red;
  color: white;
  font-size: 24px;
  padding: 8px 20px;
  border-radius: 10px;
  z-index: 999;
}
.vertical-text{
  font-size: 16px;
  transform: rotate(-90deg);
  margin: -10px;
}
.underline{
  display: inline-block;
  width: 150px;
  border-bottom: 1px solid black;
  margin-left: 10px;
  color: gray;
}
.exam-container {
  display: flex;
  width: 100%;
  background: #F9F9F9;
  justify-content: center;
  padding-bottom: 20px;
}
.exam-left-bar {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: space-around;
  height: 100vh;
}
.exam-content {
  width: 75vw;
  background: white;
  padding: 20px 40px;
  position: relative;
}
.exam-content::before {
  content: attr(data-text);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-30deg);
  font-size: 60px;
  color: rgba(0, 0, 0, 0.1);
  pointer-events: none;
  white-space: nowrap;
}
.exam-header {
  text-align: center;
  margin-bottom: 20px;
}
.exam-questions {
  border-top: 1px solid #80808047;
  padding-top: 10px;
}
.question {
  margin-bottom: 20px;
  margin-left: 20px;
}
.question ul {
  list-style: none;
  padding-left: 10px;
}
.question li {
  margin: 10px 0;
}
.score-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  font-size: 16px;
  background: #fefefe;
}
.score-table th, .score-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
}
.score-table th {
  background: #f9fbff;
  font-weight: normal;
}
.blue-text {
  font-size: 14px;
  color: gray;
  font-weight: normal;
}
.create-button {
  margin-left: auto;
  width: 130px;
  font-size: 20px;
  background-color: #244382;
  color: #fff;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.create-button:hover {
  background-color: #376edc;
}
.save-button {
  margin-right: 15px;
  width: 130px;
  font-size: 20px;
  background-color: #888;
  color: #fff;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.save-button:hover {
  background-color: #666;
}


</style>
